package com.splic.api.controller.basic;

import com.splic.common.constant.UserConstants;
import com.splic.common.core.domain.ApiResult;
import com.splic.common.enums.ErrorEnum;
import com.splic.common.utils.CodeUtils;
import com.splic.common.utils.DateUtils;
import com.splic.common.utils.ShiroUtils;
import com.splic.common.utils.StringUtils;
import com.splic.common.utils.http.HttpUtils;
import com.splic.framework.base.ApiBaseController;
import com.splic.framework.shiro.service.SysPasswordService;
import com.splic.common.core.domain.entity.SysUser;
import com.splic.system.service.ISysUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * API接口
 *
 * @author songqiang
 * @date 2019-03-08
 */
@RestController
@RequestMapping("/api/basic")
public class ApiBasicController extends ApiBaseController {


    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysPasswordService passwordService;
//    @Autowired
//    private JedisPool jedisPool;

    @RequestMapping("/getCode")
//    @ResponseBody
    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        // 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CodeUtils.generateCodeAndPic();

        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute("code", codeMap.get("code").toString());

        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            /*sos = resp.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();*/

            ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", baos);
            byte[] bytes = baos.toByteArray();//转换成字节
            BASE64Encoder encoder = new BASE64Encoder();
            String jpeg_base64 = encoder.encodeBuffer(bytes);//转换成base64串
            jpeg_base64 = jpeg_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
            resp.getWriter().write(jpeg_base64);
            baos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

   /* @RequestMapping("/login")
    public ApiResult apiLongin(HttpServletRequest request, HttpServletResponse resp) {
        Map<String, String> temp = HttpUtils.getParameterMap(request);
        if (!StringUtils.inspectBy(temp, "loginName", "password")) {
            return error(ErrorEnum.RESULT_PARAMERROR);
        }
        resp.setHeader("Access-Control-Allow-Credentials", "true");

            SysUser user = userService.selectUserByLoginName(temp.get("loginName"));
            if (user == null || !passwordService.matches(user, temp.get("password"))) {
                return error(ErrorEnum.RESULT_LOGIN_ERROR3);
            } else {
                String token = Md5Utils.hash(System.currentTimeMillis() + "" + Math.random());
                Jedis jedis = jedisPool.getResource();
                jedis.setex("KEY_LIKE_CUST_LOGIN_TOKEN:" + token, 86400, user.getLoginName());
                Map<String, Object> map = new HashMap<>();
                map.put("token", token);
                map.put("invitationCode", user.getInvitationCode());
                return success(map);
            }

    }*/

    @RequestMapping("/checkLoginName")
    public ApiResult checkLoginName(HttpServletRequest request) {
        Map<String, String> temp = HttpUtils.getParameterMap(request);
        /*if (!StringUtils.inspectBy(temp, "loginName")) {
            return error(ErrorEnum.RESULT_PARAMERROR);
        }*/
        String status = userService.checkLoginNameUnique(temp.get("loginName"));
        if (UserConstants.USER_NAME_UNIQUE.equals(status)) {
            return success();
        } else {
            return error(ErrorEnum.RESULT_LOGIN_ERROR5);
        }
    }

    @RequestMapping("/login")
    public ApiResult login(HttpServletRequest request, HttpServletResponse resp) throws Exception {
        Map<String, String> temp = HttpUtils.getParameterMap(request);

        resp.setHeader("Access-Control-Allow-Credentials", "true");
        /*if(StringUtils.isNotEmpty(temp.get("douyingId"))) {
            String status = userService.checkDouyingIdUnique(temp.get("douyingId"));
            if (UserConstants.USER_NAME_UNIQUE.equals(status)) {
                SysUser user = new SysUser();
                BeanUtils.populate(user, temp);

                user.setSalt(ShiroUtils.randomSalt());
                user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                //客户部门
                user.setDeptId((long) 203);
                //客户角色
                user.setRoleIds(new Long[]{(long) 101});
                Long maxId = userService.selectMaxId();
                if(maxId ==0){
                    maxId =  System.currentTimeMillis();
                }
                Long userId = Long.valueOf(DateUtils.dateT()+(maxId+1));
                user.setUserId(userId);

                user = userService.insertUser(user);
                String token = Md5Utils.hash(System.currentTimeMillis() + "" + Math.random());
                Jedis jedis = jedisPool.getResource();
                jedis.setex("KEY_LIKE_CUST_LOGIN_TOKEN:" + token, 86400, user.getDouyingId());
                Map<String, Object> map = new HashMap<>();
                map.put("token", token);
                SysUser sysUser = new SysUser();
                sysUser.setDouyingId(temp.get("douyingId"));
                List<SysUser> userList = userService.selectUserList(sysUser);
                map.put("userId", userId);
                *//*if (userList != null && userList.size() > 0) {
                    if (userList.get(0).getUserId().toString().length() < 2) {
                        map.put("userId", "201900" + userList.get(0).getUserId());
                    } else if (userList.get(0).getUserId().toString().length() < 3) {
                        map.put("userId", "20190" + userList.get(0).getUserId());
                    } else {
                        map.put("userId", "2019" + userList.get(0).getUserId());
                    }
                }*//*
                return success(map);
            } else {

                SysUser sysUser = new SysUser();
                sysUser.setDouyingId(temp.get("douyingId"));
                List<SysUser> userList = userService.selectUserList(sysUser);
                if (userList != null && userList.size() > 0) {
                    String token = Md5Utils.hash(System.currentTimeMillis() + "" + Math.random());
                    Jedis jedis = jedisPool.getResource();
                    jedis.setex("KEY_LIKE_CUST_LOGIN_TOKEN:" + token, 86400, userList.get(0).getDouyingId());
                    Map<String, Object> map = new HashMap<>();
                    map.put("token", token);
                    map.put("userId", userList.get(0).getUserId());

                    return success(map);
                }
            }
        }else{
            System.out.println("获取douyingId失败");
        }*/
        return null;

    }

}
